(function($){
    $.WindmillCarousel = function(el){
        var base = this;
        
        base.$el = $(el);
        base.el = el;
        
        base.$el.data("WindmillCarousel", base);
        
        base.init = function(){
        	bindTouchHandlers(base);
        };
        base.init();
    };
    
    $.fn.windmillcarousel = function(){
        return this.each(function(){
            (new $.WindmillCarousel(this));
        });
    };
    
    function positionRelevantCards(base) {
    	var lis = base.lis;
    	for (var i=0; i<lis.length; i++) {
    		if (i == base.disposition || i == base.disposition+1 || i == base.disposition-1) {
    			var diff = i - base.disposition;
    			$(lis[i]).css('opacity', 1)
    					 .css('-webkit-transform','rotateZ('+(diff+base.disposition)*base.cardRotation+'deg)');
    		} else {
    			$(lis[i]).css('opacity', 0);
    		}
    		
    	}
    }
    
    function bindTouchHandlers(base) {
    	// set carousel properties
    	var lis = $(base.$el).find('li');
    	base.lis = lis;
    	base.isAnimating = false;
    	base.disposition = 0;
    	base.maxDisposition = lis.length;
    	base.totalDispositionX = 0;
    	base.cardRotation = 70;
    	base.carouselId = Math.floor(Math.random()*1000);
    	base.idPrefix = base.carouselId+'-carousel-circle-';
    	base.clientWidth = document.body.clientWidth;
    	base.pageTransThreshold = 5; // 20 degrees 
    	
    	// init. the element as touch area
    	base.$el.touchArea();
    	
    	// style containing div
    	$(base.$el).parent().css('position', 'absolute')
    						.css('width', '100%');
    	
    	// style the carousel itself
    	$(base.$el).css('overflow', 'visible')
    			   .css('padding', 0)
    			   .css('position', 'relative')
    			   .css('left', '0%')
    			   .css('-webkit-transform-origin', '50% 200%')
    			   .css('-webkit-transition', 'all 300ms ease-in-out');
    	
    	// style each li in area 
    	for (var i=0; i<lis.length; i++) {
    		$(lis[i]).css('width', '100%')
    			  .css('height', '100%')
    			  .css('display', 'inline-block')
    			  .css('position', 'absolute')
    			  .css('-webkit-transform-origin', '50% 200%')
    			  .css('opacity', 0);
    		$(lis[i]).attr('id', base.idPrefix+'-li-'+i);
    	}
    	
    	// create dots (card markup)
    	for (var i=0, len=lis.length; i<len; i++) {
    		var circle = $('<div>').css('position', 'absolute')
			 .css('bottom', '10%')
			 .css('left', base.clientWidth/2 + (len/2-len)*10 +i*15 +'px')
			 .css('width', '10px')
			 .css('height', '10px')
			 .css('background-color', '#000')
			 .css('border-radius', '5px')
			 .css('opacity', 0.3);
    		circle.attr('id',base.idPrefix+i);
    		$(base.$el).parent().append(circle);
    	}
    	// highlight circle of first page
    	$('#'+base.idPrefix+'0').css('opacity', 1);
    	
    	// init. style cards 
    	positionRelevantCards(base);
    	
    	$(base.$el).bind('touchdragstart', function(e, data) {
    		if (base.isAnimating == true) return;
    		base.startX = data.x;
    		base.currentDispositionX = 0;
    	});
    	
    	$(base.$el).bind('touchdragmove', function(e, data) {
    		if (base.isAnimating == true) return;
    		if (data.diffX == 0) return;
    		base.isAnimating = true;
    		
    		base.totalDispositionX += data.diffX/5;
    		base.currentDispositionX += data.diffX/5;
    		
//    		$(base.el).one('webkitTransitionEnd', function() {
//    			base.isAnimating = false;
//    		});
    		setTimeout(function() {
    			base.isAnimating = false;
    		},data.durationMS+1);
    		base.$el.css('-webkit-transition', 'all '+data.durationMS+'ms linear')
    				.css('-webkit-transform', 'rotateZ('+base.totalDispositionX+'deg)');
    	});
    	
    	$(base.$el).bind('touchdragend', function(e, data) {
//    		if (base.isAnimating == true) return;
    		base.isAnimating = true;
    		
    		if ((base.currentDispositionX > 0 && base.disposition == 0) || 
    			(base.currentDispositionX < 0 && base.disposition == base.maxDisposition-1) ||
    			(Math.abs(base.currentDispositionX) < base.pageTransThreshold)) {
    			base.totalDispositionX += (-1)*base.currentDispositionX;
    		} else if (Math.abs(base.currentDispositionX) >= base.pageTransThreshold) {
    			var sign = base.currentDispositionX/Math.abs(base.currentDispositionX);
    			base.totalDispositionX += (base.cardRotation - Math.abs(base.currentDispositionX))*sign;
    			// un-highlight circle of prev page
    	    	$('#'+base.idPrefix+base.disposition).css('opacity', 0.3);
    			base.disposition += (-1)*sign;
    			// highlight circle of first page
    			$('#'+base.idPrefix+base.disposition).css('opacity', 1);
    		}
//    		$(base.el).one('webkitTransitionEnd', function() {
//    			base.isAnimating = false;
//    		});
    		setTimeout(function() {
    			// update styled cards
        		positionRelevantCards(base);
    			base.isAnimating = false;
    		},301);
    		base.$el.css('-webkit-transition', 'all 300ms ease-in-out')
					.css('-webkit-transform', 'rotateZ('+base.totalDispositionX+'deg)');
    		
    		
    	});
    }
    
})(jQuery);

$('[data-role="page"]').live('pagecreate', function() {
	var carousels = $(this).find('[data-carousel="windmill"]');
	for (var i=0; i<carousels.length; i++) {
		$(carousels[i]).windmillcarousel();
	}
});